package com.example.administrator.demoa;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private TextView txt_result;
    private EditText edtKey;
    //请求队列作全局变量，节省内存空间
    private RequestQueue requestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        requestQueue = Volley.newRequestQueue(MainActivity.this);
        txt_result = findViewById(R.id.txt_result);
        edtKey = findViewById(R.id.edt_key);
        findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = edtKey.getText().toString();
                //useVolleyStringRequestGet(phone);
                useVolleyStringRequestPost(phone);
            }
        });

        findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                useVolleyJsonRequest();
            }
        });
    }

    private void useVolleyJsonRequest() {
        //免费天气接口
        final String weatherUrl = "http://t.weather.sojson.com/api/weather/city/101280101";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(weatherUrl, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.e(TAG, jsonObject.toString());
                        //解析数据
                        try {
                            String city = jsonObject.getJSONObject("cityInfo").getString("city");
                            StringBuffer buffer = new StringBuffer();
                            buffer.append("城市：").append(city).append("\n");

                            JSONArray arr = jsonObject.getJSONObject("data").getJSONArray("forecast");
                            Log.e(TAG, "arr: "+ arr );

                            for(int i=0; i<3; i++){
                                JSONObject object = arr.getJSONObject(i);
                                String ymd = object.optString("ymd");
                                String week = object.optString("week");
                                String type = object.optString("type");
                                buffer.append(ymd).append(" ");
                                buffer.append(week).append(" ");
                                buffer.append(type).append("\n");
                            }

                            txt_result.setText(buffer.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e(TAG, volleyError.toString());
                    }
                });

        requestQueue.add(jsonObjectRequest);
    }

    private void useVolleyStringRequestPost(final String phone) {
        String phoneBaseUrl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                phoneBaseUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.e(TAG, s);
                txt_result.setText(s);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(TAG, volleyError.toString());
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("mobileCode", phone);
                map.put("userID", "");
                return map;
            }
        };

        requestQueue.add(stringRequest);
    }

    private void useVolleyStringRequestGet(String phone) {
        String url = "http://www.webxml.com.cn/zh_cn/index.aspx";
        String phoneBaseUrl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
        String phoneUrl = phoneBaseUrl.concat("?mobileCode=").concat(phone).concat("&userID=");
        StringRequest stringRequest = new StringRequest(phoneUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.e(TAG, s);
                //运行在主线程中
                txt_result.setText(s);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(TAG, volleyError.toString());
            }
        });

        //将StringRequest对象加入到RequestQueue中
        requestQueue.add(stringRequest);
    }
}
